﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;

namespace WebDiagnostics.Diagnosers.LoadedAssemblies
{
    internal class LoadedAssembliesDiagnosis : Diagnosis
    {
        public IEnumerable<LoadedAssemblyInfo> LoadedAssemblies { get; set; }

        public LoadedAssembliesDiagnosis()
        {
        }

        public LoadedAssembliesDiagnosis(IEnumerable<LoadedAssemblyInfo> loadedAssemblies)
        {
            LoadedAssemblies = loadedAssemblies;
        }

        public override void Render(TextWriter writer)
        {
            var htmlWriter = new HtmlTextWriter(writer);

            htmlWriter.RenderHeader(2, "Loaded Assemblies");

            htmlWriter.RenderBeginList("loaded-assemblies scrollable");

            foreach (var loadedAssembly in LoadedAssemblies)
                RenderListItem(loadedAssembly, htmlWriter);

            htmlWriter.RenderEndTag();
        }

        private static void RenderListItem(LoadedAssemblyInfo loadedAssembly, HtmlTextWriter writer)
        {
            writer.RenderBeginListItem("loaded-assembly");

            writer.AddAttribute(HtmlTextWriterAttribute.Title, loadedAssembly.FullName);
            writer.RenderBeginDiv();
            writer.Write("{0} ({1})", loadedAssembly.Name, loadedAssembly.Version);
            writer.RenderEndTag();

            if(loadedAssembly.References.Any())
            {
                writer.RenderBeginList("assembly-references");
                
                foreach (var assembly in loadedAssembly.References)
                    RenderListItem(assembly, writer);

                writer.RenderEndTag();
            }

            writer.RenderEndTag();
        }
    }
}